package com.example.dictionary.controller;

import com.example.dictionary.config.DictionaryProperties;
import com.example.memento.model.DictionarySource;
import com.example.dictionary.service.DictionaryDownloadService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 词典源管理控制器
 */
@RestController
@RequestMapping("/api/sources")
public class DictionarySourceController {
    
    private static final Logger log = LoggerFactory.getLogger(DictionarySourceController.class);
    
    private final DictionaryProperties properties;
    private final DictionaryDownloadService downloadService;
    
    public DictionarySourceController(DictionaryProperties properties, 
                                    DictionaryDownloadService downloadService) {
        this.properties = properties;
        this.downloadService = downloadService;
    }
    
    /**
     * 获取所有词典源配置
     */
    @GetMapping
    public ResponseEntity<List<DictionarySource>> getAllSources() {
        try {
            List<DictionarySource> sources = properties.getSources();
            return ResponseEntity.ok(sources);
        } catch (Exception e) {
            log.error("获取词典源配置失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 获取启用的词典源
     */
    @GetMapping("/enabled")
    public ResponseEntity<List<DictionarySource>> getEnabledSources() {
        try {
            List<DictionarySource> enabledSources = properties.getSources().stream()
                    .filter(DictionarySource::isEnabled)
                    .toList();
            return ResponseEntity.ok(enabledSources);
        } catch (Exception e) {
            log.error("获取启用的词典源失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 根据名称获取词典源
     */
    @GetMapping("/{name}")
    public ResponseEntity<DictionarySource> getSourceByName(@PathVariable String name) {
        try {
            Optional<DictionarySource> source = properties.getSources().stream()
                    .filter(s -> s.getName().equals(name))
                    .findFirst();
            
            return source.map(ResponseEntity::ok)
                    .orElse(ResponseEntity.notFound().build());
        } catch (Exception e) {
            log.error("获取词典源失败: {}", name, e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 启用/禁用词典源
     */
    @PutMapping("/{name}/enabled")
    public ResponseEntity<Map<String, String>> toggleSourceEnabled(@PathVariable String name, @RequestParam boolean enabled) {
        try {
            Optional<DictionarySource> sourceOpt = properties.getSources().stream()
                    .filter(s -> s.getName().equals(name))
                    .findFirst();
            
            if (sourceOpt.isPresent()) {
                DictionarySource source = sourceOpt.get();
                source.setEnabled(enabled);
                
                String message = enabled ? "词典源已启用" : "词典源已禁用";
                return ResponseEntity.ok(Map.of("message", message, "source", name, "enabled", String.valueOf(enabled)));
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            log.error("切换词典源状态失败: {}", name, e);
            return ResponseEntity.internalServerError().body(Map.of("error", e.getMessage()));
        }
    }
    
    /**
     * 添加新的词典源
     */
    @PostMapping
    public ResponseEntity<Map<String, String>> addSource(@RequestBody DictionarySource newSource) {
        try {
            // 检查是否已存在同名源
            boolean exists = properties.getSources().stream()
                    .anyMatch(s -> s.getName().equals(newSource.getName()));
            
            if (exists) {
                return ResponseEntity.badRequest()
                        .body(Map.of("error", "词典源名称已存在: " + newSource.getName()));
            }
            
            // 添加新源
            properties.getSources().add(newSource);
            
            return ResponseEntity.ok(Map.of(
                    "message", "词典源添加成功",
                    "source", newSource.getName()
            ));
        } catch (Exception e) {
            log.error("添加词典源失败", e);
            return ResponseEntity.internalServerError().body(Map.of("error", e.getMessage()));
        }
    }
    
    /**
     * 更新词典源
     */
    @PutMapping("/{name}")
    public ResponseEntity<Map<String, String>> updateSource(@PathVariable String name, @RequestBody DictionarySource updatedSource) {
        try {
            Optional<DictionarySource> sourceOpt = properties.getSources().stream()
                    .filter(s -> s.getName().equals(name))
                    .findFirst();
            
            if (sourceOpt.isPresent()) {
                DictionarySource source = sourceOpt.get();
                source.setUrl(updatedSource.getUrl());
                source.setDownloadUrl(updatedSource.getDownloadUrl());
                source.setFormat(updatedSource.getFormat());
                source.setDescription(updatedSource.getDescription());
                source.setEnabled(updatedSource.isEnabled());
                
                return ResponseEntity.ok(Map.of("message", "词典源更新成功", "source", name));
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            log.error("更新词典源失败: {}", name, e);
            return ResponseEntity.internalServerError().body(Map.of("error", e.getMessage()));
        }
    }
    
    /**
     * 删除词典源
     */
    @DeleteMapping("/{name}")
    public ResponseEntity<Map<String, String>> deleteSource(@PathVariable String name) {
        try {
            boolean removed = properties.getSources().removeIf(s -> s.getName().equals(name));
            
            if (removed) {
                return ResponseEntity.ok(Map.of("message", "词典源删除成功", "source", name));
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            log.error("删除词典源失败: {}", name, e);
            return ResponseEntity.internalServerError().body(Map.of("error", e.getMessage()));
        }
    }
    
    /**
     * 下载指定词典源
     */
    @PostMapping("/{name}/download")
    public ResponseEntity<Map<String, String>> downloadSource(@PathVariable String name) {
        try {
            Optional<DictionarySource> sourceOpt = properties.getSources().stream()
                    .filter(s -> s.getName().equals(name))
                    .findFirst();
            
            if (sourceOpt.isPresent()) {
                DictionarySource source = sourceOpt.get();
                downloadService.downloadSource(source);
                
                return ResponseEntity.ok(Map.of(
                        "message", "词典源下载任务已启动",
                        "source", name
                ));
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            log.error("下载词典源失败: {}", name, e);
            return ResponseEntity.internalServerError().body(Map.of("error", e.getMessage()));
        }
    }
    
    /**
     * 获取词典源统计信息
     */
    @GetMapping("/stats")
    public ResponseEntity<Map<String, Object>> getSourceStats() {
        try {
            List<DictionarySource> sources = properties.getSources();
            
            long totalSources = sources.size();
            long enabledSources = sources.stream().filter(DictionarySource::isEnabled).count();
            long disabledSources = totalSources - enabledSources;
            
            Map<String, Object> stats = Map.of(
                    "totalSources", totalSources,
                    "enabledSources", enabledSources,
                    "disabledSources", disabledSources,
                    "sources", sources.stream().map(source -> Map.of(
                            "name", source.getName(),
                            "enabled", source.isEnabled(),
                            "format", source.getFormat(),
                            "description", source.getDescription() != null ? source.getDescription() : ""
                    )).toList()
            );
            
            return ResponseEntity.ok(stats);
        } catch (Exception e) {
            log.error("获取词典源统计信息失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }
}
